package cn.kgc.factory;

import cn.kgc.service.AccountService;
import cn.kgc.utils.TransactionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

@Component("beanFactory")
public class BeanFactory {
    @Autowired
    private AccountService accountService;
    @Autowired
    private TransactionUtil transactionUtil;
    /**
     * 动态生成AccountService对象
     * @return
     */
    public AccountService getAccountService(){
       return (AccountService)Proxy.newProxyInstance(accountService.getClass().getClassLoader()
               , accountService.getClass().getInterfaces(), new InvocationHandler() {
           public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
               Object returnValue=null;
               try{
                   transactionUtil.beginTransaction();
                   //执行业务操作
                   returnValue=method.invoke(accountService,args);
                   transactionUtil.commitTransaction();

               }catch (Exception e){
                   e.printStackTrace();
                   transactionUtil.rollbackTransaction();
               }finally{
                   transactionUtil.closeTransaction();
               }
              return  returnValue;
           }

       });
    }



}
